<template>
  <div class="dashboard">
    <!-- 营业状态 -->
    <div class="shop-status-bar">
      <div class="status-info">
        <el-icon :size="20" :color="shopStatus === 1 ? '#67c23a' : '#909399'">
          <ShoppingBag />
        </el-icon>
        <span class="status-text">
          当前状态：<strong :class="shopStatus === 1 ? 'status-open' : 'status-close'">
            {{ shopStatus === 1 ? '营业中' : '已打烊' }}
          </strong>
        </span>
      </div>
      <el-switch
        v-model="shopStatus"
        :active-value="1"
        :inactive-value="0"
        active-text="营业"
        inactive-text="打烊"
        :before-change="handleStatusChange"
        size="large"
      />
    </div>

    <!-- 今日数据卡片 -->
    <div class="today-data">
      <div class="header-with-refresh">
        <h2 class="section-title">今日数据 <span class="date">{{ currentDate }}</span></h2>
        <div class="refresh-controls">
          <span class="last-update" v-if="lastUpdateTime">更新于 {{ formatUpdateTime(lastUpdateTime) }}</span>
          <el-button type="primary" size="small" :icon="Refresh" @click="handleRefresh" :loading="isRefreshing" circle />
        </div>
      </div>
      <div class="data-cards-column">
        <div class="data-card turnover">
          <div class="card-content">
            <div class="card-main">
              <h3>营业额</h3>
              <div class="amount">¥ {{ formatNumber(businessData.turnover) }}</div>
            </div>
            <div class="card-icon">
              <el-icon size="24" color="#43a047">
                <TrendCharts />
              </el-icon>
            </div>
          </div>
        </div>
        
        <div class="data-card orders">
          <div class="card-content">
            <div class="card-main">
              <h3>有效订单</h3>
              <div class="amount">{{ businessData.validOrderCount || 0 }}</div>
            </div>
            <div class="card-icon">
              <el-icon size="24" color="#409EFF">
                <Document />
              </el-icon>
            </div>
          </div>
        </div>

        <div class="data-card completion">
          <div class="card-content">
            <div class="card-main">
              <h3>订单完成率</h3>
              <div class="amount">{{ formatPercentage(businessData.orderCompletionRate) }}%</div>
            </div>
            <div class="card-icon">
              <el-icon size="24" color="#ff9800">
                <CircleCheck />
              </el-icon>
            </div>
          </div>
        </div>

        <div class="data-card price">
          <div class="card-content">
            <div class="card-main">
              <h3>平均客单价</h3>
              <div class="amount">¥ {{ formatNumber(businessData.unitPrice) }}</div>
            </div>
            <div class="card-icon">
              <el-icon size="24" color="#F56C6C">
                <Money />
              </el-icon>
            </div>
          </div>
        </div>

        <div class="data-card users">
          <div class="card-content">
            <div class="card-main">
              <h3>新增用户</h3>
              <div class="amount">{{ businessData.newUsers || 0 }}</div>
            </div>
            <div class="card-icon">
              <el-icon size="24" color="#9c27b0">
                <UserFilled />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作面板 -->
    <div class="quick-actions">
      <h3 class="card-title">快捷操作</h3>
      <div class="action-grid">
        <div class="action-item" @click="goToAddDish">
          <div class="action-icon">
            <el-icon size="24"><Plus /></el-icon>
          </div>
          <span class="action-label">新增菜品</span>
        </div>
        
        <div class="action-item" @click="goToAddSetmeal">
          <div class="action-icon">
            <el-icon size="24"><DocumentAdd /></el-icon>
          </div>
          <span class="action-label">新增套餐</span>
        </div>
        
        <div class="action-item" @click="goToOrders">
          <div class="action-icon">
            <el-icon size="24"><Document /></el-icon>
          </div>
          <span class="action-label">订单管理</span>
        </div>
        
        <div class="action-item" @click="goToReport">
          <div class="action-icon">
            <el-icon size="24"><DataAnalysis /></el-icon>
          </div>
          <span class="action-label">数据报表</span>
        </div>
        
        <div class="action-item" @click="goToEmployee">
          <div class="action-icon">
            <el-icon size="24"><User /></el-icon>
          </div>
          <span class="action-label">员工管理</span>
        </div>
        
        <div class="action-item" @click="goToCategory">
          <div class="action-icon">
            <el-icon size="24"><Management /></el-icon>
          </div>
          <span class="action-label">分类管理</span>
        </div>
      </div>
    </div>

    <!-- 订单管理统计 -->
    <div class="manage-card">
      <h3 class="card-title">
        订单管理
        <span class="view-more" @click="goToOrders">查看全部 →</span>
      </h3>
      <div class="order-stats">
        <div class="stat-item waiting" @click="goToOrders">
          <div class="stat-icon">
            <el-icon size="18"><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">待接单</div>
            <div class="stat-value">{{ orderOverview.waitingOrders || 0 }}</div>
          </div>
        </div>
        
        <div class="stat-item pending" @click="goToOrders">
          <div class="stat-icon">
            <el-icon size="18"><Loading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">待派送</div>
            <div class="stat-value">{{ orderOverview.deliveredOrders || 0 }}</div>
          </div>
        </div>
        
        <div class="stat-item completed" @click="goToOrders">
          <div class="stat-icon">
            <el-icon size="18"><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已完成</div>
            <div class="stat-value">{{ orderOverview.completedOrders || 0 }}</div>
          </div>
        </div>
        
        <div class="stat-item cancelled" @click="goToOrders">
          <div class="stat-icon">
            <el-icon size="18"><CloseBold /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已取消</div>
            <div class="stat-value">{{ orderOverview.cancelledOrders || 0 }}</div>
          </div>
        </div>
        
        <div class="stat-item total" @click="goToOrders">
          <div class="stat-icon">
            <el-icon size="18"><Menu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">全部订单</div>
            <div class="stat-value">{{ orderOverview.allOrders || 0 }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 菜品和套餐统计 -->
    <div class="manage-card">
      <h3 class="card-title">菜品和套餐总览</h3>
      <div class="overview-grid">
        <!-- 菜品已启售 -->
        <div class="overview-item" @click="goToDishes">
          <div class="overview-icon">
            <el-icon><Bowl /></el-icon>
          </div>
          <div class="overview-info">
            <div class="overview-label">菜品已启售</div>
            <div class="overview-count">{{ dishOverview.sold || 0 }}</div>
          </div>
          <el-button type="primary" size="small" @click.stop="goToAddDish">新增菜品</el-button>
        </div>
        
        <!-- 菜品已停售 -->
        <div class="overview-item" @click="goToDishes">
          <div class="overview-icon discontinued">
            <el-icon><Bowl /></el-icon>
          </div>
          <div class="overview-info">
            <div class="overview-label">菜品已停售</div>
            <div class="overview-count">{{ dishOverview.discontinued || 0 }}</div>
          </div>
        </div>

        <!-- 套餐已启售 -->
        <div class="overview-item" @click="goToSetmeals">
          <div class="overview-icon">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="overview-info">
            <div class="overview-label">套餐已启售</div>
            <div class="overview-count">{{ setmealOverview.sold || 0 }}</div>
          </div>
          <el-button type="primary" size="small" @click.stop="goToAddSetmeal">新增套餐</el-button>
        </div>
        
        <!-- 套餐已停售 -->
        <div class="overview-item" @click="goToSetmeals">
          <div class="overview-icon discontinued">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="overview-info">
            <div class="overview-label">套餐已停售</div>
            <div class="overview-count">{{ setmealOverview.discontinued || 0 }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="order-section">
      <div class="order-header">
        <h3 class="section-title">订单信息</h3>
        <div class="order-tabs">
          <div 
            v-for="tab in statusTabs" 
            :key="tab.status"
            :class="['tab-item', { active: currentStatus === tab.status }]"
            @click="switchStatus(tab.status)"
          >
            <span class="tab-label">{{ tab.label }}</span>
            <span class="tab-count">{{ getOrderCount(tab.status) }}</span>
          </div>
        </div>
      </div>
      
      <div v-if="filteredOrders.length > 0" class="order-list">
        <div v-for="order in filteredOrders" :key="order.id" class="order-card">
          <div class="order-left">
            <div class="order-row">
              <span class="order-label">订单号</span>
              <span class="order-value">{{ order.number }}</span>
            </div>
            <div class="order-row">
              <span class="order-label">菜品</span>
              <span class="order-value dishes" :title="order.orderDishes">{{ order.orderDishes || '暂无' }}</span>
            </div>
            <div class="order-row">
              <span class="order-label">地址</span>
              <span class="order-value address" :title="order.address">{{ order.address || '暂无' }}</span>
            </div>
            <div class="order-row">
              <span class="order-label">预计送达</span>
              <span class="order-value time">{{ formatDateTime(order.estimatedDeliveryTime) }}</span>
            </div>
          </div>
          <div class="order-right">
            <div class="order-amount">
              <span class="amount-label">实收金额</span>
              <span class="amount-value">¥{{ order.amount }}</span>
            </div>
            <div class="order-actions">
              <el-button v-if="order.status === 2" type="warning" size="small" @click="handleAcceptOrder(order.id)">
                接单
              </el-button>
              <el-button v-if="order.status === 2" type="danger" size="small" @click="handleRejectOrder(order.id)">
                拒单
              </el-button>
              <el-button v-if="order.status === 3" type="primary" size="small" @click="handleDeliveryOrder(order.id)">
                派送
              </el-button>
              <el-button v-if="order.status === 3" type="warning" size="small" @click="handleCancelOrder(order.id)">
                取消
              </el-button>
              <el-button v-if="order.status === 4" type="success" size="small" @click="handleCompleteOrder(order.id)">
                完成
              </el-button>
              <el-button v-if="order.status === 4" type="warning" size="small" @click="handleCancelOrder(order.id)">
                取消
              </el-button>
              <el-button type="text" size="small" @click="showOrderDetail(order.id)">详情</el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-orders">
        <el-empty :description="`暂无${getCurrentStatusText()}订单`" />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="800px"
      destroy-on-close
    >
      <div v-if="orderDetailLoading" class="detail-loading">
        <el-skeleton :rows="8" animated />
      </div>
      <div v-else-if="orderDetail" class="order-detail-content">
        <!-- 订单状态 -->
        <div class="detail-header">
          <el-tag :type="getStatusTagType(orderDetail.status)" size="large">
            {{ getOrderStatusText(orderDetail.status) }}
          </el-tag>
          <span class="order-number">订单号：{{ orderDetail.number }}</span>
        </div>
        
        <!-- 客户信息 -->
        <div class="detail-section">
          <h4>客户信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ orderDetail.consignee }}</span>
            </div>
            <div class="info-item">
              <span class="label">电话：</span>
              <span class="value">{{ orderDetail.phone }}</span>
            </div>
            <div class="info-item full-width">
              <span class="label">地址：</span>
              <span class="value">{{ orderDetail.address }}</span>
            </div>
          </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatDateTime(orderDetail.orderTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付状态：</span>
              <span class="value">
                <el-tag :type="orderDetail.payStatus === 1 ? 'success' : 'danger'" size="small">
                  {{ orderDetail.payStatus === 1 ? '已支付' : '未支付' }}
                </el-tag>
              </span>
            </div>
            <div class="info-item full-width">
              <span class="label">备注：</span>
              <span class="value">{{ orderDetail.remark || '无' }}</span>
            </div>
          </div>
        </div>
        
        <!-- 菜品列表 -->
        <div class="detail-section">
          <h4>菜品信息</h4>
          <el-table :data="orderDetail.orderDetailList || []" size="small">
            <el-table-column prop="name" label="菜品名称" />
            <el-table-column prop="number" label="数量" width="80" align="center" />
            <el-table-column label="金额" width="100" align="right">
              <template #default="{ row }">
                ￥{{ row.amount?.toFixed(2) || '0.00' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 金额信息 -->
        <div class="amount-info">
          <span>订单金额：</span>
          <span class="amount">￥{{ orderDetail.amount?.toFixed(2) || '0.00' }}</span>
        </div>
      </div>
      <div v-else class="detail-empty">
        <el-empty description="暂无订单详情" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { workspaceApi, orderApi, shopApi } from '@/api'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  TrendCharts, Document, CircleCheck, Money, UserFilled,
  Clock, Loading, Select, CloseBold, Menu, Bowl, Grid, Van, Refresh, Plus, DocumentAdd, User, DataAnalysis, Management, ShoppingBag 
} from '@element-plus/icons-vue'
import { initWebSocket, closeWebSocket } from '@/utils/websocket'

const router = useRouter()

// 数据状态
const businessData = ref({})
const orderOverview = ref({})
const dishOverview = ref({})
const setmealOverview = ref({})
const recentOrders = ref([])
const currentStatus = ref(2) // 默认显示待接单
const lastUpdateTime = ref(null) // 最后更新时间
const isRefreshing = ref(false) // 是否正在刷新
const refreshTimer = ref(null) // 刷新定时器
const shopStatus = ref(1) // 店铺营业状态

// 订单详情相关
const orderDetailVisible = ref(false)
const orderDetailLoading = ref(false)
const orderDetail = ref(null)

// 状态标签配置
const statusTabs = [
  { status: 2, label: '待接单' },
  { status: 3, label: '待派送' },
  { status: 4, label: '派送中' }
]

// 计算属性：过滤订单
const filteredOrders = computed(() => {
  return recentOrders.value.filter(order => order.status === currentStatus.value)
})

// 当前日期
const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}.${month}.${day}`
})

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0'
  return Number(num).toLocaleString()
}

// 格式化百分比
const formatPercentage = (num) => {
  if (!num && num !== 0) return '0.0'
  // 如果值大于1，说明后端返回的已经是百分比值
  if (num > 1) {
    return Number(num).toFixed(1)
  }
  // 如果值在0-1之间，需要乘以100转为百分比
  return (Number(num) * 100).toFixed(1)
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 切换状态
const switchStatus = (status) => {
  currentStatus.value = status
}

// 获取当前状态的订单数量
const getOrderCount = (status) => {
  return recentOrders.value.filter(order => order.status === status).length
}

// 获取当前状态文本
const getCurrentStatusText = () => {
  const tab = statusTabs.find(t => t.status === currentStatus.value)
  return tab ? tab.label : ''
}

// 格式化更新时间
const formatUpdateTime = (date) => {
  const now = new Date()
  const diff = Math.floor((now - date) / 1000) // 秒数差
  
  if (diff < 60) {
    return '刚刚'
  } else if (diff < 3600) {
    return `${Math.floor(diff / 60)} 分钟前`
  } else {
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${hours}:${minutes}`
  }
}

// 手动刷新
const handleRefresh = async () => {
  isRefreshing.value = true
  try {
    await Promise.all([
      loadDashboardData(),
      loadRecentOrders()
    ])
    ElMessage.success('数据已刷新')
  } finally {
    isRefreshing.value = false
  }
}

// 加载工作台数据
const loadDashboardData = async () => {
  try {
    console.log('开始加载工作台数据...')
    
    const [businessRes, orderRes, dishRes, setmealRes] = await Promise.all([
      workspaceApi.businessData(),
      workspaceApi.overviewOrders(), 
      workspaceApi.overviewDishes(),
      workspaceApi.overviewSetmeals()
    ])

    console.log('API响应数据:', {
      businessRes: businessRes,
      orderRes: orderRes,
      dishRes: dishRes,
      setmealRes: setmealRes
    })

    // 正确解析API响应数据
    businessData.value = businessRes.data?.data || businessRes.data || {}
    orderOverview.value = orderRes.data?.data || orderRes.data || {}
    dishOverview.value = dishRes.data?.data || dishRes.data || {}
    setmealOverview.value = setmealRes.data?.data || setmealRes.data || {}
    
    // 更新最后刷新时间
    lastUpdateTime.value = new Date()

    console.log('工作台数据设置完成:', {
      business: businessData.value,
      orders: orderOverview.value,
      dishes: dishOverview.value,
      setmeals: setmealOverview.value
    })
  } catch (error) {
    console.error('加载工作台数据失败:', error)
    ElMessage.error('加载工作台数据失败: ' + (error.response?.data?.msg || error.message || '未知错误'))
    
    // 如果API调用失败，使用默认值
    businessData.value = {
      turnover: 0,
      validOrderCount: 0,
      orderCompletionRate: 0,
      unitPrice: 0,
      newUsers: 0
    }
    orderOverview.value = {
      waitingOrders: 0,
      deliveredOrders: 0,
      completedOrders: 0,
      cancelledOrders: 0,
      allOrders: 0
    }
    dishOverview.value = { sold: 0, discontinued: 0 }
    setmealOverview.value = { sold: 0, discontinued: 0 }
  }
}

// 加载最新订单数据
const loadRecentOrders = async () => {
  try {
    const response = await orderApi.conditionSearch({
      page: 1,
      pageSize: 20,
      status: '',
      number: '',
      phone: '',
      beginTime: '',
      endTime: ''
    })
    
    console.log('最新订单数据:', response)
    const orders = response.data?.data?.records || response.data?.records || []
    recentOrders.value = orders
  } catch (error) {
    console.error('加载最新订单失败:', error)
    recentOrders.value = []
  }
}

// 导航方法
const goToOrders = () => {
  router.push('/orders')
}

const goToDishes = () => {
  router.push('/dish')
}

const goToSetmeals = () => {
  router.push('/setmeal')
}

const goToAddDish = () => {
  router.push('/dish/add')
}

const goToAddSetmeal = () => {
  router.push('/setmeal/add')
}

const goToReport = () => {
  router.push('/report')
}

const goToEmployee = () => {
  router.push('/employee')
}

const goToCategory = () => {
  router.push('/category')
}

// 订单操作方法
const handleAcceptOrder = async (orderId) => {
  try {
    await orderApi.confirm({ id: orderId })
    ElMessage.success('接单成功')
    loadRecentOrders() // 重新加载订单数据
  } catch (error) {
    console.error('接单失败:', error)
    ElMessage.error('接单失败: ' + (error.response?.data?.msg || error.message))
  }
}

const handleRejectOrder = async (orderId) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入拒单原因', '拒单确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '拒单原因不能为空'
    })
    
    await orderApi.rejection({ id: orderId, rejectionReason: value })
    ElMessage.success('拒单成功')
    loadRecentOrders() // 重新加载订单数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒单失败:', error)
      ElMessage.error('拒单失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

const handleDeliveryOrder = async (orderId) => {
  try {
    await orderApi.delivery(orderId)
    ElMessage.success('派送成功')
    loadRecentOrders() // 重新加载订单数据
  } catch (error) {
    console.error('派送失败:', error)
    ElMessage.error('派送失败: ' + (error.response?.data?.msg || error.message))
  }
}

const handleCancelOrder = async (orderId) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '取消原因不能为空'
    })
    
    await orderApi.cancel({ id: orderId, cancelReason: value })
    ElMessage.success('取消订单成功')
    loadRecentOrders() // 重新加载订单数据
    loadDashboardData() // 刷新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

const handleCompleteOrder = async (orderId) => {
  try {
    await orderApi.complete(orderId)
    ElMessage.success('订单已完成')
    loadRecentOrders() // 重新加载订单数据
    loadDashboardData() // 刷新统计数据
  } catch (error) {
    console.error('完成订单失败:', error)
    ElMessage.error('完成订单失败: ' + (error.response?.data?.msg || error.message))
  }
}

// 获取营业状态切换
const handleStatusChange = async (value) => {
  try {
    const action = value === 1 ? '开始营业' : '打烊'
    await ElMessageBox.confirm(
      `确定要${action}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await shopApi.setStatus(value)
    // 修改成功后重新获取最新状态
    await getShopStatus()
    // 修正成功消息文本
    const successMsg = value === 1 ? '已开始营业' : '已打烊'
    ElMessage.success(successMsg)
    return true
  } catch (error) {
    if (error === 'cancel') {
      return false
    }
    console.error('设置营业状态失败:', error)
    ElMessage.error('设置营业状态失败')
    return false
  }
}

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  orderDetailLoading.value = true
  orderDetail.value = null
  
  try {
    console.log('开始获取订单详情，订单ID:', orderId)
    const response = await orderApi.details(orderId)
    console.log('订单详情原始响应:', response)
    
    // 正确解析响应数据
    const res = response.data || response
    
    if (res && res.code === 1 && res.data) {
      orderDetail.value = res.data
      console.log('成功获取订单详情:', res.data)
    } else {
      console.error('获取订单详情失败:', res?.msg || '未知错误')
      ElMessage.error('获取订单详情失败: ' + (res?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取订单详情异常:', error)
    ElMessage.error('获取订单详情失败: ' + (error.message || '网络错误'))
  } finally {
    orderDetailLoading.value = false
  }
}

// 显示订单详情
const showOrderDetail = async (orderId) => {
  if (!orderId) {
    console.warn('订单ID为空，无法获取详情')
    return
  }
  
  orderDetailVisible.value = true
  await fetchOrderDetail(orderId)
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '待接单', 
    3: '已接单',
    4: '派送中',
    5: '已完成',
    6: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const tagTypeMap = {
    1: 'warning',
    2: 'warning',
    3: 'primary',
    4: 'primary',
    5: 'success',
    6: 'info'
  }
  return tagTypeMap[status] || 'info'
}

// 开始定时刷新
const startAutoRefresh = () => {
  refreshTimer.value = setInterval(() => {
    loadDashboardData()
    loadRecentOrders()
  }, 30000) // 30秒
}

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = null
  }
}

// 获取店铺状态
const getShopStatus = async () => {
  try {
    const res = await shopApi.getStatus()
    console.log('获取店铺状态返回:', res)
    // 增加更多判断，确保正确获取状态值
    if (res?.data?.data !== undefined) {
      shopStatus.value = parseInt(res.data.data) || 0
    } else if (res?.data !== undefined) {
      shopStatus.value = parseInt(res.data) || 0
    } else {
      shopStatus.value = 0
    }
    console.log('当前店铺状态设置为:', shopStatus.value)
  } catch (error) {
    console.error('获取店铺状态失败:', error)
    shopStatus.value = 0
  }
}

onMounted(() => {
  loadDashboardData()
  loadRecentOrders()
  getShopStatus()
  
  // 启动定时刷新
  startAutoRefresh()
  
  // 初始化 WebSocket 连接
  const userId = localStorage.getItem('userId') || '1'
  initWebSocket(userId, (message) => {
    console.log('收到 WebSocket 消息:', message)
    // 收到消息后刷新数据
    loadRecentOrders()
    loadDashboardData()
  })
  
  // 添加简单的订单通知监听
  window.addEventListener('new-order-received', (event) => {
    console.log('收到新订单通知:', event.detail)
    // 只刷新数据，不显示通知（通知由 OrderNotification 组件统一处理）
    loadRecentOrders()
    loadDashboardData()
  })
  
  window.addEventListener('order-reminder-received', (event) => {
    console.log('收到催单通知:', event.detail)
    // 只刷新数据，不显示通知（通知由 OrderNotification 组件统一处理）
    loadRecentOrders()
  })
})

// 组件卸载时清理
import { onUnmounted } from 'vue'
onUnmounted(() => {
  stopAutoRefresh()
  closeWebSocket()
  // 清理事件监听
  window.removeEventListener('new-order-received', () => {})
  window.removeEventListener('order-reminder-received', () => {})
})
</script>

<style scoped>
.dashboard {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  width: 100%;
}

/* 营业状态栏样式 */
.shop-status-bar {
  background: white;
  border-radius: 12px;
  padding: 16px 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-text {
  font-size: 14px;
  color: #606266;
}

.status-text strong {
  font-weight: 600;
  margin-left: 4px;
}

.status-open {
  color: #67c23a;
}

.status-close {
  color: #909399;
}

.today-data {
  margin-bottom: 32px;
}

.header-with-refresh {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.refresh-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.last-update {
  font-size: 12px;
  color: #909399;
}

.section-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 12px;
}

.date {
  font-size: 14px;
  font-weight: normal;
  color: #909399;
}

/* 一行布局的数据卡片 */
.data-cards-column {
  display: flex;
  flex-direction: row;
  gap: 16px;
  margin-bottom: 32px;
  flex-wrap: nowrap;
  width: 100%;
  align-items: stretch;
}

.data-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  height: 120px;
  flex: 1 1 20%;
  min-width: 0;
  position: relative;
  overflow: hidden;
}

.data-card:hover {
  box-shadow: 0 8px 30px 0 rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
  border-color: #e1f3ff;
}

.data-card:hover .card-icon {
  transform: scale(1.1);
}

.data-card.turnover:hover {
  border-color: #c8e6c9;
}

.data-card.orders:hover {
  border-color: #bbdefb;
}

.data-card.completion:hover {
  border-color: #ffe0b2;
}

.data-card.price:hover {
  border-color: #ffcdd2;
}

.data-card.users:hover {
  border-color: #e1bee7;
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
  z-index: 2;
}

.card-main {
  flex: 1;
}

.card-main h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.amount {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.card-icon {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.1);
  position: relative;
}

/* 不同类型卡片的图标颜色 */
.data-card.turnover .card-icon {
  background: rgba(67, 160, 71, 0.15);
}

.data-card.orders .card-icon {
  background: rgba(64, 158, 255, 0.15);
}

.data-card.completion .card-icon {
  background: rgba(255, 152, 0, 0.15);
}

.data-card.price .card-icon {
  background: rgba(245, 108, 108, 0.15);
}

.data-card.users .card-icon {
  background: rgba(156, 39, 176, 0.15);
}

.mt-24 {
  margin-top: 24px;
}

.mt-16 {
  margin-top: 16px;
}

.manage-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.card-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.view-more {
  font-size: 14px;
  font-weight: 400;
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s ease;
}

.view-more:hover {
  color: #337ecc;
  text-decoration: underline;
}

.order-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fafbfc;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.stat-item:hover {
  background: #f0f9ff;
  border-color: #409EFF;
}

.stat-item.pending:hover { background: #fff3e0; border-color: #ff9800; }
.stat-item.waiting:hover { background: #f3e5f5; border-color: #9c27b0; }
.stat-item.delivering:hover { background: #e3f2fd; border-color: #2196f3; }
.stat-item.completed:hover { background: #e8f5e8; border-color: #4caf50; }
.stat-item.cancelled:hover { background: #ffebee; border-color: #f44336; }
.stat-item.total:hover { background: #e3f2fd; border-color: #2196f3; }

.stat-icon {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.1);
}

.stat-item.pending .stat-icon {
  background: rgba(255, 152, 0, 0.15);
  color: #ff9800;
}

.stat-item.waiting .stat-icon {
  background: rgba(156, 39, 176, 0.15);
  color: #9c27b0;
}

.stat-item.delivering .stat-icon {
  background: rgba(33, 150, 243, 0.15);
  color: #2196f3;
}

.stat-item.completed .stat-icon {
  background: rgba(76, 175, 80, 0.15);
  color: #4caf50;
}

.stat-item.cancelled .stat-icon {
  background: rgba(244, 67, 54, 0.15);
  color: #f44336;
}

.stat-item.total .stat-icon {
  background: rgba(33, 150, 243, 0.15);
  color: #2196f3;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.overview-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.overview-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fafbfc;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
  flex: 1;
  min-width: 200px;
}

.overview-item:hover {
  background: #f0f9ff;
  border-color: #409EFF;
}

.overview-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.overview-icon.discontinued {
  background: linear-gradient(135deg, #909399, #b3b8bd);
  box-shadow: 0 2px 8px rgba(144, 147, 153, 0.3);
}

.overview-info {
  flex: 1;
  margin-right: 12px;
}

.overview-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.overview-count {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

/* 响应式设计 */
@media (min-width: 1600px) {
  .dashboard {
    padding: 32px 5%;
  }
  
  .data-card {
    padding: 24px;
    height: 130px;
  }
  
  .amount {
    font-size: 32px;
  }
}

@media (min-width: 1400px) {
  .data-card {
    min-width: 200px;
  }
}

@media (max-width: 1200px) {
  .data-cards-column {
    flex-wrap: wrap;
  }
  
  .data-card {
    min-width: 160px;
    max-width: none;
    height: auto;
    min-height: 100px;
  }
  
  .amount {
    font-size: 24px;
  }

  .card-icon {
    width: 45px;
    height: 45px;
  }
  
  .action-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 900px) {
  .data-cards-column {
    gap: 12px;
  }
  
  .data-card {
    min-width: 140px;
    padding: 16px;
  }
  
  .amount {
    font-size: 22px;
  }
  
  .action-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 16px;
  }
  
  .shop-status-bar {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .status-info {
    width: 100%;
    justify-content: center;
  }
  
  .data-cards-column {
    flex-direction: column;
    gap: 16px;
  }
  
  .data-card {
    min-width: auto;
    flex: none;
    height: 100px;
    padding: 16px;
  }
  
  .amount {
    font-size: 22px;
  }

  .card-icon {
    width: 40px;
    height: 40px;
  }
  
  .overview-grid {
    flex-direction: column;
  }
  
  .overview-item {
    min-width: auto;
    flex: none;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .order-tabs {
    width: 100%;
    justify-content: space-between;
    gap: 8px;
  }
  
  .tab-item {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .order-card {
    flex-direction: column;
    gap: 16px;
  }
  
  .order-right {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-amount {
    text-align: left;
  }
  
  .order-value.dishes,
  .order-value.address {
    max-width: 200px;
  }
  
  .order-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .section-title {
    font-size: 18px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-stats {
    grid-template-columns: 1fr;
  }
  
  .manage-card {
    padding: 16px;
  }
  
  .stat-item, .overview-item {
    padding: 12px;
  }
  
  .stat-value, .overview-count {
    font-size: 18px;
  }
  
  .action-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .action-item {
    min-width: auto;
    min-height: 80px;
    padding: 16px 12px;
  }
  
  .action-icon {
    width: 36px;
    height: 36px;
    font-size: 18px;
    margin-bottom: 8px;
  }
  
  .action-label {
    font-size: 12px;
  }
  
  .quick-actions {
    padding: 16px;
  }
  
  .header-with-refresh {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .refresh-controls {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}

/* 订单管理区域样式 */
.order-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.order-header .section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.order-tabs {
  display: flex;
  gap: 20px;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f5f7fa;
  border: 1px solid transparent;
}

.tab-item:hover {
  background: #e1f0ff;
}

.tab-item.active {
  background: #409EFF;
  color: white;
}

.tab-label {
  font-size: 14px;
  font-weight: 500;
}

.tab-count {
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tab-item.active .tab-count {
  background: rgba(255, 255, 255, 0.3);
}

.tab-item:not(.active) .tab-count {
  background: #909399;
  color: white;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background: #fafbfc;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  position: relative;
}

.order-card:hover {
  background: #f5f7fa;
  border-color: #409EFF;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.08);
}

.order-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-label {
  width: 70px;
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
}

.order-value {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.order-value.dishes,
.order-value.address {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 300px;
}

.order-value.time {
  color: #F56C6C;
  font-weight: 500;
}

.order-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.order-amount {
  text-align: right;
}

.amount-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
  display: block;
}

.amount-value {
  font-size: 20px;
  font-weight: bold;
  color: #F56C6C;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.empty-orders {
  padding: 60px 0;
  text-align: center;
}

/* 快捷操作面板样式 */
.quick-actions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 16px;
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f0f0f0;
  min-height: 100px;
  position: relative;
  overflow: hidden;
}

.action-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent, rgba(64, 158, 255, 0.05));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.action-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
  border-color: #409EFF;
}

.action-item:hover::before {
  opacity: 1;
}

.action-item:hover .action-icon {
  transform: scale(1.1) rotate(5deg);
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  color: white;
}

.action-item:active {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.action-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 12px;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  background: linear-gradient(135deg, #f5f7fa, #e4e7ed);
  color: #606266;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 1;
}

/* 为不同的操作项添加独特的颜色 */
.action-item:nth-child(1):hover .action-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.action-item:nth-child(2):hover .action-icon {
  background: linear-gradient(135deg, #e6a23c, #f0b354);
}

.action-item:nth-child(3):hover .action-icon {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
}

.action-item:nth-child(4):hover .action-icon {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.action-item:nth-child(5):hover .action-icon {
  background: linear-gradient(135deg, #9c27b0, #ba68c8);
}

.action-item:nth-child(6):hover .action-icon {
  background: linear-gradient(135deg, #00bcd4, #26c6da);
}

.action-label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  text-align: center;
  position: relative;
  z-index: 1;
}

/* 订单详情对话框样式 */
.order-detail-content {
  padding: 20px;
}

.detail-loading {
  padding: 40px;
}

.detail-empty {
  padding: 60px;
  text-align: center;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-number {
  font-size: 14px;
  color: #909399;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.full-width {
  grid-column: span 2;
}

.info-item .label {
  font-size: 14px;
  color: #909399;
  margin-right: 8px;
  flex-shrink: 0;
  width: 80px;
}

.info-item .value {
  font-size: 14px;
  color: #303133;
  flex: 1;
}

.amount-info {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  font-size: 16px;
}

.amount-info .amount {
  font-size: 20px;
  font-weight: 600;
  color: #f56c6c;
  margin-left: 10px;
}
</style> 